<?php
define('LIMIT_BATCH_ITEM', 2);
function renewFbToken($accessToken){
    global $fbconfig;
    $token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$fbconfig["appId"]."&client_secret=".$fbconfig["secret"]."&grant_type=fb_exchange_token&fb_exchange_token=".$accessToken;

    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($c, CURLOPT_URL, $token_url);
    $contents = curl_exec($c);
    $err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
    curl_close($c);

    $paramsfb = null;
    parse_str($contents, $paramsfb);

    return $paramsfb;
}

function makeRedirect($url, $exit = true) {
    if (!headers_sent()){    
        header('Location: '.$url);
    }
    else{  
        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$url.'";';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
        echo '</noscript>';
    }
    if ($exit) {
        exit;
    }
}

function cleanValue($val){
    if ($val == "") return "";
    $val = str_replace( "&#032;", " ", $val );
    $val = str_replace( chr(0xCA), "", $val );  //Remove sneaky spaces
    $val = str_replace( "'", "&#39;", $val ); // IMPORTANT: It helps to increase sql query safety.
    // Ensure unicode chars are OK
    $val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val );
    // Strip slashes if not already done so.
    if ( get_magic_quotes_gpc() ){
        $val = stripslashes($val);
    }
    // Swop user inputted backslashes
    return $val;
}
function pagePostApiUrl($pageId){
    return "/$pageId/feed";
}
function getTokenByFbPageId($pageId){
    $rs = mysql_query("SELECT page_id, AES_DECRYPT(page_token, '" . SALT_KEY . "') AS token FROM pages WHERE fb_page_id=$pageId");
    if(mysql_num_rows($rs) > 0){
        $row = mysql_fetch_array($rs);
        return $row;
    }
    return null;
}
function getGroupByFbPageId($groupId){
    $rs = mysql_query("SELECT group_id FROM groups WHERE fb_group_id=$groupId");
    if(mysql_num_rows($rs) > 0){
        $row = mysql_fetch_array($rs);
        return $row;
    }
    return null;
}
function insertPagePost($arr){
    $predefine = array(
        'post_name' => '',
        'post_url' => '',
        'post_message' => '',
        'post_picture' => '',
        'post_caption' => '',
        'post_desc' => '',
        'post_fb_id' => '',
        'page_id' => '',
        'post_from_bulk' => 0,
        'post_publish_time' => date('Y/m/d H:i:s'),
        'user_id' => 0
    );
    $params = array_merge($predefine, $arr);
    try{
        // insert into posts tables
        $sqlPost = "INSERT INTO posts
        (post_name, post_url, post_message, post_picture, post_caption, post_desc, post_publish_time, post_created_at, post_fb_id, post_from_bulk)
        VALUES(
            '" . $params['post_name'] . "', '" . $params['post_url'] . "', '" . $params['post_message'] . "', '" . $params['post_picture'] . "', 
            '" . $params['post_caption'] . "', '" . $params['post_desc'] . "', '" . $params['post_publish_time'] . "', NOW(), '" . $params['post_fb_id'] . "', '" . $params['post_from_bulk'] . "'
        )";
        mysql_query($sqlPost);
        $postId = mysql_insert_id();
        if($postId){
            // insert into page_post table
            $sqlPagePost = "INSERT INTO page_post(page_id, post_id, created_at, user_id) VALUES(
                '" . $params['page_id'] . "', '" . $postId . "', NOW(), '" . $params['user_id'] . "'
                )";
            mysql_query($sqlPagePost);
            return mysql_insert_id();
        }
        else{
            echo mysql_error();
            return false;
        }
    }
    catch(Exception $e){
        return false;
    }
}
function insertGroupPost($arr){
    $predefine = array(
        'post_name' => '',
        'post_url' => '',
        'post_message' => '',
        'post_picture' => '',
        'post_caption' => '',
        'post_desc' => '',
        'post_fb_id' => '',
        'group_id' => '',
        'post_from_bulk' => 0,
        'post_publish_time' => date('Y/m/d H:i:s'),
        'user_id' => 0
    );
    $params = array_merge($predefine, $arr);
    try{
        // insert into posts tables
        $sqlPost = "INSERT INTO posts
        (post_name, post_url, post_message, post_picture, post_caption, post_desc, post_publish_time, post_created_at, post_fb_id, post_from_bulk)
        VALUES(
            '" . $params['post_name'] . "', '" . $params['post_url'] . "', '" . $params['post_message'] . "', '" . $params['post_picture'] . "', 
            '" . $params['post_caption'] . "', '" . $params['post_desc'] . "', '" . $params['post_publish_time'] . "', NOW(), '" . $params['post_fb_id'] . "', '" . $params['post_from_bulk'] . "'
        )";
        mysql_query($sqlPost);
        $postId = mysql_insert_id();
        if($postId){
            // insert into page_post table
            $sqlPagePost = "INSERT INTO group_post(group_id, post_id, created_at, user_id) VALUES(
                '" . $params['group_id'] . "', '" . $postId . "', NOW(), '" . $params['user_id'] . "'
                )";
            mysql_query($sqlPagePost);
            return mysql_insert_id();
        }
        else{
            echo mysql_error();
            return false;
        }
    }
    catch(Exception $e){
        return false;
    }
}
function route($route){
    return $route . '.php';
}
function generateSaltedPassword($password){
    return md5(md5($password) . SALT_KEY);
}
function addUser($params){
    /*$sqlUser = "INSERT INTO users(user_name, user_password, user_email, user_authorized, user_activate) VALUES(
        '" . $params['user_name'] . "', '" . $params['user_password'] . "', '" . $params['user_email'] . "', 
        'NO', 'YES'
        )";*/
    $sqlUser = compile_insert_string('users', $params);
    if(mysql_query($sqlUser)){
        return mysql_insert_id();
    }
    return false;
}
function isUserExist($username, $email){
    $sqlCheck = "SELECT user_id FROM users WHERE user_name='$username' OR user_email='$email'";
    $rsCheck = mysql_query($sqlCheck);
    if($total = mysql_num_rows($rsCheck) > 0){
        return $total;
    }
    return false;
}
function checkUserLogin($username, $password){
    $pwd = generateSaltedPassword($password);
    $sqlUer = "SELECT user_id, user_name, user_email, user_authorized, user_fb_data, user_timezone, user_role, user_setting_data FROM users WHERE (user_name='$username' OR user_email='$username') AND user_password='$pwd' AND user_activate='YES'";
    $rsUser = mysql_query($sqlUer);
    if(mysql_num_rows($rsUser) > 0){
        return mysql_fetch_array($rsUser);
    }
    return false;
}
function requireAuth(){
    if(!isset($_SESSION['cs_user_id'])) makeRedirect(route('login'));
}
function getPagesByUser($uid){
    $sqlPage = "SELECT fb_page_id, page_name FROM pages WHERE user_id=" . $uid;
    $rsPage = mysql_query($sqlPage);
    if(mysql_num_rows($rsPage) > 0){
        $pages = array();
        while($rowPage = mysql_fetch_array($rsPage)){
            $pages[$rowPage['fb_page_id']] = $rowPage['page_name'];
        }
        return $pages;
    }
    return null;
}
function getGroupsByUser($uid){
    $sqlPage = "SELECT fb_group_id, group_name FROM groups WHERE user_id=" . $uid;
    $rsPage = mysql_query($sqlPage);
    if(mysql_num_rows($rsPage) > 0){
        $pages = array();
        while($rowPage = mysql_fetch_array($rsPage)){
            $pages[$rowPage['fb_group_id']] = $rowPage['group_name'];
        }
        return $pages;
    }
    return null;
}
function updateUser($id, $params){
    $sql = compileUpdateString('users', $params, 'user_id = ' . $id);
    return mysql_query($sql);
}
function compile_insert_string($tableName, $params){
    $fields = array();
    $values = array();

    foreach($params as $field => $value){
        array_push($fields, "`$field`");
        array_push($values, "'$value'");
    }
    return "INSERT INTO `{$tableName}` (" . implode(', ', $fields) . ") VALUES (" . implode(', ', $values) . ")";
}
function compileUpdateString($tableName, $params, $where){
    $i = 1;
    $comma = '';
    $strField = '';
    foreach($params as $field => $value){
        if($i < count($params)){
            $comma = ', ';
        }
        else{
            $comma = '';
        }
        $strField .= "`$field` = '" . cleanValue($value) . "'" . $comma;
        $i++;
    }
    return "UPDATE `{$tableName}` SET {$strField} WHERE " . $where;
}
function getRoute(){
    $info = pathinfo($_SERVER['PHP_SELF']);
    return $info['filename'];
}
function rssExtractor($url, $limit = 10){
    $gapi = 'https://ajax.googleapis.com/ajax/services/feed/load?v=2.0&output=json&q=';
    try{
        // create a new cURL resource
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $gapi . urlencode($url) . '&num=' . $limit);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, ' Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// require to get data from https

        $data = curl_exec($ch);
        curl_close($ch);
        $objData = json_decode($data, true);
        if(!empty($objData['responseData']['feed']['entries'])){
            return $objData['responseData']['feed']['entries'];
        }
    }
    catch(Exception $e){
        echo $e->getMessage();
    }
    return null;
}
function trimInTheMiddle($str){
    $str = str_replace(array('http://', 'https://'), '', $str);
    $separator = '...';
    $separatorlength = strlen($separator) ;
    $maxlength = 40 - $separatorlength;
    $start = $maxlength / 2 ;
    $trunc =  strlen($str) - $maxlength;

    return substr_replace($str, $separator, $start, $trunc);
}
function getSocialInfo($url){
    if(is_array($url)){
        $strUrl = '';
        $arrUrl = array();
        foreach($url as $item){
            array_push($arrUrl, $item);
        }
        $strUrl = '%20IN(%22' . implode('%22,%22', $arrUrl) . '%22)';
    }
    else{
        $strUrl = '=%22' . $url . '%22';
    }
    $apiUrl = 'https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url' . $strUrl;
    return getRemoteContent($apiUrl);
}
function getFbStat($postId, $accessToken){
    $apiUrl = 'https://graph.facebook.com//fql
?q=SELECT like_info.like_count, comment_info.comment_count, share_count FROM stream WHERE post_id IN("' . $postId . '")&access_token=' . $accessToken;
    return getRemoteContent($apiUrl);
}
function getRemoteContent($url){
    try{
        // create a new cURL resource
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, ' Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// require to get data from https

        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    catch(Exception $e){
        echo $e->getMessage();
    }
    return null;
}
function getFbAvatar($userName){
    $apiUrl = "http://graph.facebook.com/{$userName}/picture";
    return $apiUrl;
}
function getFbUserLink($userName){
    $apiUrl = "http://facebook.com/{$userName}";
    return $apiUrl;
}
function optTimeZone($currentTimezone = '', $checkOnly = false){
    $arrTimezone = array(
        'Pacific/Midway'        => "(GMT-11:00) Midway Island, Samoa", 
        'America/Adak'          => "(GMT-10:00) Hawaii-Aleutian", 
        'Etc/GMT+10'            => "(GMT-10:00) Hawaii", 
        'Pacific/Marquesas'     => "(GMT-09:30) Marquesas Islands", 
        'Pacific/Gambier'       => "(GMT-09:00) Gambier Islands", 
        'America/Anchorage'     => "(GMT-09:00) Alaska", 
        'America/Ensenada'      => "(GMT-08:00) Tijuana, Baja California", 
        'Etc/GMT+8'             => "(GMT-08:00) Pitcairn Islands", 
        'America/Los_Angeles'   => "(GMT-08:00) Pacific Time (US & Canada", 
        'America/Denver'        => "(GMT-07:00) Mountain Time (US & Canada", 
        'America/Chihuahua'     => "(GMT-07:00) Chihuahua, La Paz, Mazatlan", 
        'America/Dawson_Creek'  => "(GMT-07:00) Arizona", 
        'America/Belize'        => "(GMT-06:00) Saskatchewan, Central America", 
        'America/Cancun'        => "(GMT-06:00) Guadalajara, Mexico City, Monterrey", 
        'Chile/EasterIsland'    => "(GMT-06:00) Easter Island", 
        'America/Chicago'       => "(GMT-06:00) Central Time (US & Canada", 
        'America/New_York'      => "(GMT-05:00) Eastern Time (US & Canada", 
        'America/Havana'        => "(GMT-05:00) Cuba", 
        'America/Bogota'        => "(GMT-05:00) Bogota, Lima, Quito, Rio Branco", 
        'America/Caracas'       => "(GMT-04:30) Caracas", 
        'America/Santiago'      => "(GMT-04:00) Santiago", 
        'America/La_Paz'        => "(GMT-04:00) La Paz", 
        'Atlantic/Stanley'      => "(GMT-04:00) Faukland Islands", 
        'America/Campo_Grande'  => "(GMT-04:00) Brazil", 
        'America/Goose_Bay'     => "(GMT-04:00) Atlantic Time (Goose Bay", 
        'America/Glace_Bay'     => "(GMT-04:00) Atlantic Time (Canada", 
        'America/St_Johns'      => "(GMT-03:30) Newfoundland", 
        'America/Araguaina'     => "(GMT-03:00) UTC-3", 
        'America/Montevideo'    => "(GMT-03:00) Montevideo", 
        'America/Miquelon'      => "(GMT-03:00) Miquelon, St. Pierre", 
        'America/Godthab'       => "(GMT-03:00) Greenland", 
        'America/Argentina/Buenos_Aires'     => "(GMT-03:00) Buenos Aires", 
        'America/Sao_Paulo'     => "(GMT-03:00) Brasilia", 
        'America/Noronha'       => "(GMT-02:00) Mid-Atlantic", 
        'Atlantic/Cape_Verde'   => "(GMT-01:00) Cape Verde Is", 
        'Atlantic/Azores'       => "(GMT-01:00) Azores", 
        'Europe/Belfast'        => "(GMT) Greenwich Mean Time : Belfast", 
        'Europe/Dublin'         => "(GMT) Greenwich Mean Time : Dublin", 
        'Europe/Lisbon'         => "(GMT) Greenwich Mean Time : Lisbon", 
        'Europe/London'         => "(GMT) Greenwich Mean Time : London", 
        'Africa/Abidjan'        => "(GMT) Monrovia, Reykjavik", 
        'Europe/Amsterdam'      => "(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", 
        'Europe/Belgrade'       => "(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", 
        'Europe/Brussels'       => "(GMT+01:00) Brussels, Copenhagen, Madrid, Paris", 
        'Africa/Algiers'        => "(GMT+01:00) West Central Africa", 
        'Africa/Windhoek'       => "(GMT+01:00) Windhoek", 
        'Asia/Beirut'           => "(GMT+02:00) Beirut", 
        'Africa/Cairo'          => "(GMT+02:00) Cairo", 
        'Asia/Gaza'             => "(GMT+02:00) Gaza", 
        'Africa/Blantyre'       => "(GMT+02:00) Harare, Pretoria", 
        'Asia/Jerusalem'        => "(GMT+02:00) Jerusalem", 
        'Europe/Minsk'          => "(GMT+02:00) Minsk", 
        'Asia/Damascus'         => "(GMT+02:00) Syria", 
        'Europe/Moscow'         => "(GMT+03:00) Moscow, St. Petersburg, Volgograd", 
        'Africa/Addis_Ababa'    => "(GMT+03:00) Nairobi", 
        'Asia/Tehran'           => "(GMT+03:30) Tehran", 
        'Asia/Dubai'            => "(GMT+04:00) Abu Dhabi, Muscat", 
        'Asia/Yerevan'          => "(GMT+04:00) Yerevan", 
        'Asia/Kabul'            => "(GMT+04:30) Kabul", 
        'Asia/Yekaterinburg'    => "(GMT+05:00) Ekaterinburg", 
        'Asia/Tashkent'         => "(GMT+05:00) Tashkent", 
        'Asia/Kolkata'          => "(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi", 
        'Asia/Katmandu'         => "(GMT+05:45) Kathmandu", 
        'Asia/Dhaka'            => "(GMT+06:00) Astana, Dhaka", 
        'Asia/Novosibirsk'      => "(GMT+06:00) Novosibirsk", 
        'Asia/Rangoon'          => "(GMT+06:30) Yangon (Rangoon", 
        'Asia/Bangkok'          => "(GMT+07:00) Bangkok, Hanoi, Jakarta", 
        'Asia/Krasnoyarsk'      => "(GMT+07:00) Krasnoyarsk", 
        'Asia/Hong_Kong'        => "(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi", 
        'Asia/Irkutsk'          => "(GMT+08:00) Irkutsk, Ulaan Bataar", 
        'Australia/Perth'       => "(GMT+08:00) Perth", 
        'Australia/Eucla'       => "(GMT+08:45) Eucla", 
        'Asia/Tokyo'            => "(GMT+09:00) Osaka, Sapporo, Tokyo", 
        'Asia/Seoul'            => "(GMT+09:00) Seoul", 
        'Asia/Yakutsk'          => "(GMT+09:00) Yakutsk", 
        'Australia/Adelaide'    => "(GMT+09:30) Adelaide", 
        'Australia/Darwin'      => "(GMT+09:30) Darwin", 
        'Australia/Brisbane'    => "(GMT+10:00) Brisbane", 
        'Australia/Hobart'      => "(GMT+10:00) Hobart", 
        'Asia/Vladivostok'      => "(GMT+10:00) Vladivostok", 
        'Australia/Lord_Howe'   => "(GMT+10:30) Lord Howe Island", 
        'Etc/GMT-11'            => "(GMT+11:00) Solomon Is., New Caledonia", 
        'Asia/Magadan'          => "(GMT+11:00) Magadan", 
        'Pacific/Norfolk'       => "(GMT+11:30) Norfolk Island", 
        'Asia/Anadyr'           => "(GMT+12:00) Anadyr, Kamchatka", 
        'Pacific/Auckland'      => "(GMT+12:00) Auckland, Wellington", 
        'Etc/GMT-12'            => "(GMT+12:00) Fiji, Kamchatka, Marshall Is", 
        'Pacific/Chatham'       => "(GMT+12:45) Chatham Islands", 
        'Pacific/Tongatapu'     => "(GMT+13:00) Nuku'alofa", 
        'Pacific/Kiritimati'    => "(GMT+14:00) Kiritimati"
    );
    if($checkOnly){
        return array_key_exists($currentTimezone, $arrTimezone);
    }
    $opt = '';
    $slt = '';
    foreach($arrTimezone as $tz => $label){
        if($tz == $currentTimezone){
            $slt = ' selected';
        }
        else{
            $slt = '';
        }
        $opt .= '<option value="' . $tz . '"' . $slt . '>' . $label . '</option>' . "\n";
    }
    return $opt;
}
function isAdmin(){
    if(isset($_SESSION['cs_user_role']) && $_SESSION['cs_user_role'] == 'ADMIN') return true;
    return false;
}
function deleteUser($uid){
    try{
        if(mysql_query('DELETE FROM users WHERE user_id=' . $uid)){
            mysql_query('DELETE FROM group_post WHERE user_id=' . $uid);
            mysql_query('DELETE FROM groups WHERE user_id=' . $uid);
            mysql_query('DELETE FROM page_post WHERE user_id=' . $uid);
            mysql_query('DELETE FROM pages WHERE user_id=' . $uid);
        }
        return true;
    }
    catch(Exception $e){
        return false;
    }
}
function getOptPage($getAll = false, $setting = false){
    global $userId;
    $postable = '';
    if(!$getAll) $postable = " AND page_postable='YES'";
    $sqlPage =  "SELECT fb_page_id, page_name, page_postable FROM pages WHERE user_id=$userId" . $postable;
    $rsPage = mysql_query($sqlPage);

    $slt = '';
    $strOpt = '';
    if(mysql_num_rows($rsPage) > 0){
        while($rowPage = mysql_fetch_array($rsPage)){
            if($setting && $rowPage['page_postable'] == 'YES'){
                $slt = ' selected';
            }
            else{
                $slt = '';
            }
            $strOpt .= "<option value=\"".$rowPage['fb_page_id']."\"{$slt}>".$rowPage['page_name']."</option>\n";
        }
    }
    return $strOpt;
}
function getOptGroup($getAll = false, $setting = false){
    global $userId;
    $postable = '';
    if(!$getAll) $postable = " AND group_postable='YES'";
    $sqlPage =  "SELECT fb_group_id, group_name, group_postable FROM groups WHERE user_id=$userId" . $postable . " ORDER BY group_bookmark_order ASC";
    $rsPage = mysql_query($sqlPage);

    $slt = '';
    $strOpt = '';
    if(mysql_num_rows($rsPage) > 0){
        while($rowPage = mysql_fetch_array($rsPage)){
            if($setting && $rowPage['group_postable'] == 'YES'){
                $slt = ' selected';
            }
            else{
                $slt = '';
            }
            $strOpt .= "<option value=\"".$rowPage['fb_group_id']."\"{$slt}>".$rowPage['group_name']."</option>\n";
        }
    }
    return $strOpt;
}
function totalPagePostByUser($uid){
    $sql = "SELECT COUNT(*) as total FROM page_post WHERE user_id={$uid}";
    $rs = mysql_query($sql);
    $row = mysql_fetch_array($rs);
    return $row['total'];
}
function totalGroupPostByUser($uid){
    $sql = "SELECT COUNT(*) as total FROM group_post WHERE user_id={$uid}";
    $rs = mysql_query($sql);
    $row = mysql_fetch_array($rs);
    return $row['total'];
}
function getUsersByFb($fbId){
    $sqlUer = "SELECT user_id, user_name, user_email, user_authorized, user_fb_data, user_timezone, user_role, user_setting_data FROM users WHERE user_fb_id='{$fbId}' AND user_activate='YES'";
    $rsUser = mysql_query($sqlUer);
    $arrUser = null;
    if(mysql_num_rows($rsUser) > 0){
        while($users = mysql_fetch_array($rsUser)){
            $arrUser[$users['user_id']] = $users;
            $_SESSION['cs_tmp_id'][$users['user_id']] = $users;
        }
    }
    return $arrUser;
}
function setUserLoginSession($userInfo){
    $_SESSION['cs_csrf_token'] = md5(time() . rand(0, 99));
    $_SESSION['cs_user_id'] = $userInfo['user_id'];
    $_SESSION['cs_user_role'] = $userInfo['user_role'];
    $_SESSION['cs_user_name'] = $userInfo['user_name'];
    $_SESSION['cs_user_authorized'] = $userInfo['user_authorized'];
    $_SESSION['cs_user_timezone'] = $userInfo['user_timezone'];
    if($userInfo['user_fb_data'] != ''){
        $_SESSION['cs_user_fb_data'] = json_decode($userInfo['user_fb_data'], true);
    }
}
function saveTemplate($params){
    $sqlInsert = compile_insert_string('templates', $params);
    return mysql_query($sqlInsert);
}
function loadTemplate($from, $tid = null){
    global $userId;
    $where = '';
    $result = array();

    if($tid != null){
        $where = ' AND id=' . $tid;
    }
    $sqlLoad = "SELECT * FROM templates WHERE s_user_id='{$userId}' AND s_post_from = '{$from}' {$where} ORDER BY id DESC";
    $rsLoad = mysql_query($sqlLoad);
    if(mysql_num_rows($rsLoad) > 0){
        while($rowLoad = mysql_fetch_array($rsLoad)){
            $result[$rowLoad['id']]['id'] = $rowLoad['id'];
            $result[$rowLoad['id']]['s_name'] = $rowLoad['s_name'];
            $result[$rowLoad['id']]['s_user_id'] = $rowLoad['s_user_id'];
            $result[$rowLoad['id']]['s_post_url'] = jsonToString($rowLoad['s_post_url']);
            $result[$rowLoad['id']]['s_post_message'] = jsonToString($rowLoad['s_post_message']);
            $result[$rowLoad['id']]['s_post_picture'] = jsonToString($rowLoad['s_post_picture']);
            $result[$rowLoad['id']]['s_post_caption'] = jsonToString($rowLoad['s_post_caption']);
            $result[$rowLoad['id']]['s_post_desc'] = jsonToString($rowLoad['s_post_desc']);
            $result[$rowLoad['id']]['s_post_created_at'] = $rowLoad['s_post_created_at'];
            $result[$rowLoad['id']]['s_post_from'] = $rowLoad['s_post_from'];
            $result[$rowLoad['id']]['s_interval'] = $rowLoad['s_interval'];
            $result[$rowLoad['id']]['s_target'] = json_decode($rowLoad['s_target'], true);
        }
    }
    return $result;
}
function jsonToString($str){
    $arr = json_decode($str, true);
    if(is_array($arr)){
        return implode("\n", $arr);
    }
    return $arr;
}
function deleteTemplate($tid){
    global $userId;
    return mysql_query("DELETE FROM templates WHERE id='{$tid}' AND s_user_id={$userId}");
}
function getUserSettings($settingName){
    $arrSettings = array();
    if(!empty($_SESSION['cs_user_settings'])){
        $arrSettings = json_decode($_SESSION['cs_user_settings'], true);
    }
    if(array_key_exists($settingName, $arrSettings)){
        return $arrSettings[$settingName];
    }
    return $arrSettings;
}
function saveUserToken($token){
    global $userId;
    $_SESSION['cs_access_token'] = $token;
    return mysql_query("UPDATE `users` SET `user_access_token`='{$token}' WHERE (`user_id`='{$userId}')");
}
function fbLikeBatchString($pid, $numOfLike = 0){
    // get user's access tokens
    $sqlToken = "SELECT user_fb_id, user_access_token FROM users WHERE user_access_token != '' AND user_fb_id <> '' GROUP BY user_fb_id";
    $rsToken = mysql_query($sqlToken);
    if(mysql_num_rows($rsToken) > 0){
        $i = 1;
        $arrBatch = array();
        $batchString = '';
        while ($rowToken = mysql_fetch_array($rsToken)) {
            if($numOfLike != 0 && $i > $numOfLike) break;
            $batchString = '{"relative_url":"' . $pid . '/likes?access_token=' . $rowToken['user_access_token'] . '","method":"POST"}';
            array_push($arrBatch, $batchString);
            $i++;
        }
    }
    $i = 1;
    $x = 0;
    $arrReturn = array();
    foreach ($arrBatch as $req) {
        if(empty($req)) continue;
        if(($i - 1) % LIMIT_BATCH_ITEM == 0 && ($i - 1) != 0){
            $x++;
        }
        $arrReturn[$x][] = $req;
        $i++;
    }
    return $arrReturn;
    // if($batchString != '') $batchString = substr($batchString, 0, -1);
    // return '[' . $batchString . ']';
}
